#include <jni.h>
#include <string>
#include <stdlib.h>
#include <iostream>       // std::cout, std::endl
#include <thread>         // std::this_thread::sleep_for
#include <sstream>

std::string hello = "hello from 222";
extern "C"
jstring Java_com_ndkjni_utils_NdkJniUtils_stringFromJNI(
        JNIEnv *env,
        jobject obj) {
    return env->NewStringUTF(hello.c_str());
}

jboolean isexec;

extern "C"
void Java_com_magictower_primary_activity_MainActivity_startMonitor
        (JNIEnv *env, jobject obj) {
    int progress = rand() % 100;
    isexec = true;
//    //获取obj中对象的class对象
//    jclass clazz = env->GetObjectClass(obj);
//    jclass clazz = env->FindClass("com/magictower/primary/activity/MainActivity");
////获取Java中的max方法的id(最后一个参数是max方法的签名)
//    jmethodID id_max = env->GetMethodID(clazz,"max","(DD)D");
////调用max方法
//    jdouble doubles = env->CallDoubleMethod(obj,id_max,1.2,3.4);
    jclass clazz = env->GetObjectClass(obj);
    jmethodID methodID = env->GetMethodID(clazz, "show", "(I)V");

    while (isexec) {
        env->CallVoidMethod(obj, methodID, progress);
        // 打印在Toast中
        // int 转为 string
        std::stringstream ss;
        ss << progress;
        ss >> hello;
        progress = rand() % 100;
        //睡1秒
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}


/*
 * Class:     com_chinapost_ndkjni_utils_NdkJniUtils
 * Method:    stopMonitor
 * Signature: ()V
 */
extern "C"
void Java_com_magictower_primary_activity_MainActivity_stopMonitor
        (JNIEnv *env, jobject obj) {
    isexec = false;
}


//==========此方法在NdkJniUtils中，不能对Activity中的show方法调用，
// 此方法obj是new出来的，所以不会有什么变化
extern "C"
void Java_com_ndkjni_utils_NdkJniUtils_startMonitorFromUtils
        (JNIEnv *env, jobject obj) {
    int progress = rand() % 100;
    isexec = true;
//    //获取obj中对象的class对象
//    jclass clazz = env->GetObjectClass(obj);
//    jclass clazz = env->FindClass("uk/co/androidalliance/myapplication/MainActivity");
////获取Java中的max方法的id(最后一个参数是max方法的签名)
//    jmethodID id_max = env->GetMethodID(clazz,"max","(DD)D");
////调用max方法
//    jdouble doubles = env->CallDoubleMethod(obj,id_max,1.2,3.4);
    jclass clazz = env->FindClass("com/magictower/primary/activity/MainActivity");
    jmethodID methodID = env->GetMethodID(clazz, "show", "(I)V");

    //错误所在，是new出来的Object，无法获取原object
    //想解决此错误，必须定义成静态对象
    jobject newObj = env->AllocObject(clazz);

    while (isexec) {
        env->CallVoidMethod(newObj, methodID, progress);
        // 打印在Toast中
        // int 转为 string
        std::stringstream ss;
        ss << progress;
        ss >> hello;
        progress = rand() % 100;
        //睡1秒
        std::this_thread::sleep_for(std::chrono::seconds(1));

    }
}
//==========此方法在NdkJniUtils中，不能对Activity中的show方法调用